﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;

using System.Linq.Expressions;
using Newtonsoft.Json;
using OA.Core;
using OA.Model;
using OA.BLL;
using OA.Web.Areas.Member.Controllers;

using Z.EntityFramework.Plus;
using Microsoft.Extensions.Caching.Memory;
using OA.Web.Code;
using Microsoft.AspNetCore.Http;
using OA.Web.Attribute;
using Microsoft.AspNetCore.Mvc;
using OA.Core.EF;
using OA.Core.Helper;
using X.PagedList;
using OA.Model.DB;

namespace OA.Web.Areas.Management.Controllers
{
    [Area("Management")]
    public class TestPaperController : BaseMemberController
    {

        private IMemoryCache _cache;
        public TestPaperController(ICookie cookie, IHttpContextAccessor accessor, IMemoryCache cache) : base(accessor, cookie, cache)
        {
            _cache = cache;
        }

        [MyActionFilter("206008", "试卷管理", "管理中心", true, "iconshijuan1")]
        public IActionResult Index()
        {
            return View();
        }

        [MyActionFilter("206008", "投票管理")]
        public IActionResult GetData(string keyword, int page = 1, int limit = 15)
        {
            Expression<Func<TestPaper, bool>> where = m => true;
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                where = m => (m.Title.Contains(keyword));
            }
            var list = this.dbContextFactory.DbContext.TestPapers.Where(where).Select(SimpleTestPaper.Map).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);
        }

        [MyActionFilter("206008001", "添加试卷", "试卷管理", false, "")]
        [HttpGet]
        public IActionResult Create()
        {
            return View(new TestPaper() { StartTime = DateTime.Now, EndTime = DateTime.Now });
        }

        [MyActionFilter("206008001", "添加试卷", "试卷管理", false, "")]
        [HttpPost]
        public IActionResult Create(TestPaper model)
        {
            BaseResult baseResult = new BaseResult();
            if (!ModelState.IsValid)
            {
                baseResult.State = 400;
                baseResult.Msg = this.GetModelStateError(ModelState);
                return Json(baseResult);
            }
            else
            {
                this.AddInfo<TestPaper>(model);
                baseResult.Msg = "添加试卷成功";
                return Json(baseResult);

            }

        }

        [HttpGet]
        [MyActionFilter("206008002", "编辑试卷", "试卷管理", false, "")]
        public IActionResult Edit(int id)
        {
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(id);
            if (infoTestPaper == null)
            {
                return Redirect("/Management/TestPaper?msg=沒有找到该试卷");
            }
            return View(infoTestPaper);
        }

        [HttpPost]
        [MyActionFilter("206008002", "编辑试卷", "试卷管理", false, "")]
        public IActionResult Edit(int id, TestPaper model)
        {
            BaseResult baseResult = new BaseResult();
            if (!ModelState.IsValid)
            {
                baseResult.State = 400;
                baseResult.Msg = this.GetModelStateError(ModelState);
                return Json(baseResult);
            }
            TestPaper infoPageGroup = this.GetInfo<TestPaper>(id);
            if (infoPageGroup == null)
            {
                baseResult.State = 400;
                baseResult.Msg = "沒有找到该试卷";
                return Json(baseResult);
            }
            this.Update<TestPaper>(infoPageGroup, model, null, new string[] { "ID", "TestPaperItemContent" });
            baseResult.Msg = "试卷修改成功";
            return Json(baseResult);

        }

        [HttpGet]
        [MyActionFilter("206008003", "删除试卷", "试卷管理", false, "")]
        public IActionResult Delete(int id)
        {
            Expression<Func<TestPaper, bool>> where = m => m.ID == id;
            this.Delete<TestPaper>(where);
            return Json(new { State = 200, Msg = "试卷删除成功" });
        }

        [HttpGet]
        [MyActionFilter("206008004", "试卷项管理", "试卷管理", false, "")]
        public IActionResult ShowItems(int id)
        {
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(id);
            ViewBag.TestPaper = infoTestPaper;
            List<TestPaperItem> items = new List<TestPaperItem>();
            if (!string.IsNullOrWhiteSpace(infoTestPaper.ExamTopicContent))
            {
                items = JsonHelper.DeserializeList<TestPaperItem>(infoTestPaper.ExamTopicContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<TestPaperItem>() { new TestPaperItem() { } };
            }
            return View(items);
        }

        [HttpPost]
        [MyActionFilter("206008004", "试卷项管理", "试卷管理", false, "")]
        public IActionResult ShowItems(int id, List<TestPaperItem> TestPaperItems)
        {
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(id);
            if (TestPaperItems == null || TestPaperItems.Count == 0)
            {

            }
            var result = TestPaperItems.Where(m => m.Status != -1 && !string.IsNullOrWhiteSpace(m.Title)).OrderBy(m => m.Sort).ToList();
            int index = 1;
            foreach (TestPaperItem item in TestPaperItems)
            {
                item.ID = index;
                if (string.IsNullOrWhiteSpace(item.ItemContent))
                {
                    item.Type = 3;
                }
                index++;
            }
            TestPaper updateTestPaper = new TestPaper();
            updateTestPaper.Score = result.Sum(m => m.Score);
            updateTestPaper.ExamTopicContent = JsonConvert.SerializeObject(result);
            this.Update<TestPaper>(infoTestPaper, updateTestPaper, new string[] { "ExamTopicContent", "Score" });
            return Redirect($"/Management/TestPaper/ShowTestPaper/{id}");
        }

        [HttpGet]
        [MyActionFilter("206008005", "查看试卷", "试卷管理", false, "")]
        public IActionResult ShowTestPaper(int id)
        {
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(id);
            ViewBag.TestPaper = infoTestPaper;
            List<TestPaperItem> items = new List<TestPaperItem>();
            if (!string.IsNullOrWhiteSpace(infoTestPaper.ExamTopicContent))
            {
                items = JsonHelper.DeserializeList<TestPaperItem>(infoTestPaper.ExamTopicContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<TestPaperItem>() { new TestPaperItem() { } };
            }
            return View(items);
        }

        [HttpPost]
        public IActionResult ShowTestPaper(int id, List<TestPaperItem> Item)
        {
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(id);
            ViewBag.TestPaper = infoTestPaper;
            List<TestPaperItem> items = new List<TestPaperItem>();
            if (!string.IsNullOrWhiteSpace(infoTestPaper.ExamTopicContent))
            {
                items = JsonHelper.DeserializeList<TestPaperItem>(infoTestPaper.ExamTopicContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<TestPaperItem>() { new TestPaperItem() { } };
            }
            return View(items);
        }

        [HttpGet]
        [MyActionFilter("206008006", "设置成员", "试卷管理", false, "")]
        public IActionResult SetEmployees(int id)
        {
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(id);
            ViewBag.TestPaper = infoTestPaper;
            return View();
        }

        [HttpPost]
        [MyActionFilter("206008006", "设置成员", "试卷管理", false, "")]
        public IActionResult SetEmployees(int id, List<string> employees)
        {
            BaseResult baseResult = new BaseResult();
            var dbContext = this.dbContextFactory.DbContext;
            var currentList = dbContext.EmployeeTestPaper.Where(m => m.TestPaperID == id).Select(m => m.EmpID).ToList();
            employees = employees.Where(m => !string.IsNullOrWhiteSpace(m)).ToList();
            var deletes = currentList.Where(m => !employees.Contains(m)).ToList();

            var addList = employees.Where(m => !currentList.Contains(m)).ToList();

            TestPaper infoTestPaper = this.GetInfo<TestPaper>(id);
            ViewBag.TestPaper = infoTestPaper;
            List<EmployeeTestPaper> items = new List<EmployeeTestPaper>();
            foreach (string employee in addList)
            {
                EmployeeTestPaper item = new EmployeeTestPaper();
                item.CreateDateTime = DateTime.Now;
                item.EmpID = employee;
                item.Status = 0;
                item.TestPaperID = id;
                items.Add(item);
            }

            using (var trn = dbContext.Database.BeginTransaction())
            {
                try
                {
                    dbContext.EmployeeTestPaper.AddRange(items);
                    if (deletes.Count > 0)
                    {
                        Expression<Func<EmployeeTestPaper, bool>> where = m => m.TestPaperID == id && deletes.Contains(m.EmpID);
                        dbContext.EmployeeTestPaper.Where(where).Delete();
                    }
                    dbContext.SaveChanges();
                    trn.Commit();
                    baseResult.Msg = "人员指定成功";
                    return Json(baseResult);

                }
                catch (Exception ex)
                {
                    trn.Rollback();
                    baseResult.Msg = ex.ToString();
                    return Json(baseResult);
                }
            }

        }

        [MyActionFilter("206008007", "试卷统计", "试卷管理", false, "")]
        public IActionResult Statistics(int id, string keyWord,int p = 1, int size = 12)
        {
            ViewBag.ID = id;
            return View();
        }

        [MyActionFilter("206008007", "试卷统计", "试卷管理", false, "")]
        public IActionResult GetStatisticsData(int id,string keyWord, int page = 1, int limit = 15)
        {
            Expression<Func<EmployeeTestPaperView, bool>> where = m => m.TestPaperID == id;
            if (!string.IsNullOrWhiteSpace(keyWord))
            {
                where = where.AndAlso<EmployeeTestPaperView>(m => m.EmpID == keyWord || m.EmpName == keyWord);
            }
            var list = this.dbContextFactory.DbContext.EmployeeTestPaperView.Where(where).OrderByDescending(m => m.ID).ToPagedList(page, limit);
            var result = new
            {
                code = "0",
                msg = "",
                count = list.TotalItemCount,
                data = list
            };
            return Json(result);
        }


        [MyActionFilter("206008007", "试卷统计", "试卷管理", false, "")]
        public IActionResult Show(int id)
        {
            EmployeeTestPaper infoEmployeeTestPaper = this.dbContextFactory.DbContext.EmployeeTestPaper.Where(m => m.ID == id).FirstOrDefault();
            TestPaper infoTestPaper = this.GetInfo<TestPaper>(infoEmployeeTestPaper.TestPaperID);
            List<EmployeeTestPaperSelect> listResult = this.dbContextFactory.DbContext.EmployeeTestPaperSelect.Where(m => m.TestPaperID == infoTestPaper.ID && m.EmpID == Info.EmpID).ToList();
            ViewBag.TestPaper = infoTestPaper;
            List<TestPaperItem> items = new List<TestPaperItem>();
            if (!string.IsNullOrWhiteSpace(infoTestPaper.ExamTopicContent))
            {
                items = JsonHelper.DeserializeList<TestPaperItem>(infoTestPaper.ExamTopicContent);
            }
            if (items == null || items.Count == 0)
            {
                items = new List<TestPaperItem>() { new TestPaperItem() { } };
            }
            ViewBag.Result = listResult;
            return View(items);

        }
        
        


        [HttpGet]
        public IActionResult GetEmployeeTree(int id)
        {
            var selects = this.dbContextFactory.DbContext.EmployeeTestPaper.Where(m => m.TestPaperID == id).Select(m => m.EmpID).ToList();
            var departments = this.dbContextFactory.DbContext.Department.Select(m => new SimpleDepartment2 { ID = m.ID, Name = m.Name, ParentDepartmentID = m.ParentDepartmentID }).ToList();
            var employeePositions = this.dbContextFactory.DbContext.Database.SqlQuery<Employee8>("select * from  EmployeeTree").ToList();

            List<MyTree> list = new List<MyTree>();

            var topDepartment = departments.Where(m => m.ParentDepartmentID == 0).ToList();
            foreach (var department in topDepartment)
            {
                MyTree tree = new MyTree();
                tree.t = department.Name;
                tree.d = new List<MyTree>();
                tree.v = "";
                CEmployee.InintEmployeeTree(tree, department.ID, departments, employeePositions, selects);
                list.Add(tree);
            }
            return Json(list);
        }

    }
}